package com.yonyou.jrmob.contacts.schedule.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yonyou.jrmob.contacts.R;
import com.yonyou.jrmob.contacts.schedule.adapter.SelectDptAdapter;
import com.yonyou.jrmob.contacts.schedule.utils.CharacterParser;
import com.yonyou.jrmob.contacts.schedule.utils.PinyinComparator;
import com.yonyou.jrmob.contacts.schedule.vo.ContactEntity;
import com.yonyou.jrmob.contacts.schedule.vo.ContactsVO;
import com.yonyou.jrmob.contacts.schedule.vo.SelectContactsVO;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.login.bean.MAServices_lib;
import jrmob.yonyou.com.commonlib.view.TextWatcherEx;
import jrmob.yonyou.com.commonlib.view.auto.AutoCompleteEditView;

public class SelectDepartmentActivity extends BaseActivityMob_lib {

	/* private SearchView mSearchView; */
	// private IndexableStickyListView mIndexableStickyListView;
	private ListView lv_persondeteil;
	private Button btn_queren;
	private Button button_left;


	private List<ContactEntity> mContacts;
	private SharedPreferences mSharedPreferences = null;
	private List<ContactsVO> contactsList;
	private List<ContactsVO> contactsListDpartment;
	private CharacterParser characterParser;
	private PinyinComparator pinyinComparator;
	private SelectDptAdapter adapter;
	private AutoCompleteEditView searchView;
	private AutoCompleteTextView tv;
	private List<ContactsVO> contactsListSelect = new ArrayList<ContactsVO>();//搜索后选择的参与人
	private ArrayList<SelectContactsVO> allContactsListSelect = new ArrayList<SelectContactsVO>();//所有选择的参与人
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initActionbar();
		setContentView(R.layout.activity_department);
		initView();
		initSerach();
		initData();
	}

	@Override
	public void initListener() {

	}

	@Override
	protected void onResume() {
		super.onResume();
		StatusBarUtil.setStatusBarColor(this, R.color.schedule_status_bar_bg);
	}

	List<SelectContactsVO> selectContactsVOList = new ArrayList<SelectContactsVO>();
	public void initData(){
		selectContactsVOList = getIntent().getExtras().getParcelableArrayList("Selected");
		callService();
	}

	public void initView() {
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		btn_queren = (Button) findViewById(R.id.button_right);
		button_left = (Button) findViewById(R.id.button_left);
		searchView = (AutoCompleteEditView) findViewById(R.id.search_view_pledge);
		tv = searchView.getTv();

		button_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		lv_persondeteil = (ListView) findViewById(R.id.lv_persondeteil);

		lv_persondeteil.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

			}
		});

		btn_queren.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SelectDepartmentActivity.this,
						ScheduleMainActivity.class);
				//StringBuffer nameBuffer = new StringBuffer();
				//StringBuffer pkBuffer = new StringBuffer();
				/*for (int i = 0; i < adapter.getCount(); i++) {
					if (adapter.getItem(i).getIscheck()) {
						nameBuffer.append(adapter.getItem(i).getContactName()).append(",");
						pkBuffer.append(adapter.getItem(i).getCuserId()).append(",");
					}
				}*/




				if (null == contactsList||contactsList.size() == 0){

				}else {
					for (int i = 0 ; i<contactsList.size();i++){
						if (contactsList.get(i).getIscheck()){

							SelectContactsVO contactsVO = new SelectContactsVO();
							contactsVO.setContactName(contactsList.get(i).getContactName().trim());
							contactsVO.setCuserId(contactsList.get(i).getCuserId());
							allContactsListSelect.add(contactsVO);
							//nameBuffer.append(contactsList.get(i).getContactName().trim()).append(",");
							//pkBuffer.append(contactsList.get(i).getCuserId()).append(",");
						}
					}
				}

				if (null == contactsListSelect||contactsListSelect.size() == 0){

				}else {
					for (int i = 0 ; i<contactsListSelect.size();i++){
						if (contactsListSelect.get(i).getIscheck()){
							SelectContactsVO contactsVO = new SelectContactsVO();
							contactsVO.setContactName(contactsListSelect.get(i).getContactName().trim());
							contactsVO.setCuserId(contactsListSelect.get(i).getCuserId());
							allContactsListSelect.add(contactsVO);
							//nameBuffer.append(contactsListSelect.get(i).getContactName().trim()).append(",");
							//pkBuffer.append(contactsListSelect.get(i).getCuserId()).append(",");
						}
					}
				}

				if (null == contactsListDpartment||contactsListDpartment.size() == 0){

				}else {
					for (int i = 0 ; i<contactsListDpartment.size();i++){
						if (contactsListDpartment.get(i).getIscheck()){
							SelectContactsVO contactsVO = new SelectContactsVO();
							contactsVO.setContactName(contactsListDpartment.get(i).getContactName().trim());
							contactsVO.setCuserId(contactsListDpartment.get(i).getCuserId());
							allContactsListSelect.add(contactsVO);
							//nameBuffer.append(contactsListDpartment.get(i).getContactName().trim()).append(",");
							//pkBuffer.append(contactsListDpartment.get(i).getCuserId()).append(",");
						}
					}
				}

				if (null == selectContactsVOList||selectContactsVOList.size() == 0){

				}else {
					for (int i = 0 ; i<selectContactsVOList.size();i++){
						if (selectContactsVOList.get(i).getIschange() != true){

							SelectContactsVO contactsVO = new SelectContactsVO();
							contactsVO.setContactName(selectContactsVOList.get(i).getContactName().trim());
							contactsVO.setCuserId(selectContactsVOList.get(i).getCuserId());
							allContactsListSelect.add(contactsVO);
							//nameBuffer.append(contactsList.get(i).getContactName().trim()).append(",");
							//pkBuffer.append(contactsList.get(i).getCuserId()).append(",");
						}
					}
				}

				Bundle bundle = new Bundle();
				bundle.putParcelableArrayList("allSelect", allContactsListSelect);
				intent.putExtras(bundle);
				setResult(44, intent);
				finish();
			}
		});
	}

	/***
	 * 调用后台服务
	 */
	private void callService() {

		JSONObject json = new JSONObject();
		try {
			json.put("transtype", Constant.TRANSTYPE_DEPT);
			json.put("user_code", getUserInfoLRY().getUser_code());
			json.put("tenant_id", getUserInfoLRY().getTenant_id());
			json.put("uuidToken", Constant.TOKEN);
			if (!CommonUtil.isNetworkConnected(this)) {
				CommonUtil.showToast(this, "当前网络不可用,请检查!");
				return;
			}
			MAServices_lib.callMACommonService(this, new ServiceCallback() {
				@Override
				public void execute(JSONObject json) {
					JSONObject jsObject;
					JSONArray jsArray;
					try {
						jsObject = (JSONObject) json.opt("result");
						Object obj = jsObject.opt("retflag");
						// 有错误的时候
						if (null != obj && obj.toString().trim().equals("1")) {
							String msg = jsObject.optString("msg").toString().trim();
							showMessage(msg);
							if(msg.contains("请重新登录")){
								turnToLoginActivity(SelectDepartmentActivity.this);
							}
							return;
						}
						jsArray = (JSONArray) jsObject.get("contacalist");
						//contactsList = new ArrayList<ContactsVO>();
						contactsListDpartment = new ArrayList<ContactsVO>();
						for (int i = 0; i < jsArray.length(); i++) {
							ContactsVO contacts = new ContactsVO();
							contacts.setContactName(jsArray.getJSONObject(i).getString("user_name"));
							contacts.setVdef(jsArray.getJSONObject(i).getString("user_mobilephone"));
							contacts.setContactTel(jsArray.getJSONObject(i).getString("user_telephone"));
							contacts.setUser_email(jsArray.getJSONObject(i).getString("user_email"));
							contacts.setCuserId(jsArray.getJSONObject(i).getString("cuserid"));
							//contactsList.add(contacts);
							contactsListDpartment.add(contacts);
						}
						/*for(int i = 0; i < selectContactsVOList.size();i++){

						}*/
						contactsListDpartment = filledData(contactsListDpartment);
						Collections.sort(contactsListDpartment, pinyinComparator);
						adapter = new SelectDptAdapter(SelectDepartmentActivity.this, contactsListDpartment,selectContactsVOList);
						lv_persondeteil.setAdapter(adapter);
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
				}

				@Override
				public void error(String arg0, String arg1) {
					// 设置登录按钮可用性(登录请求后台有反应后可用)
					Toast.makeText(SelectDepartmentActivity.this, arg0 + arg1,
							Toast.LENGTH_LONG).show();
					/*adapter = new SelectDptAdapter(SelectDepartmentActivity.this, new ArrayList<ContactsVO>());
					lv_persondeteil.setAdapter(adapter);*/
				}
			}, json);

		} catch (Exception e) {
			// 设置登录按钮可用性(登录请求后台有反应后可用)
			Log.e("mmmm", e + "");
			e.printStackTrace();
		}
	}


	public void initSerach(){

		// 删除图标
		searchView.getIv().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchView.getTv().setText("");
			}
		});
		// 输入的文本
		searchView.getTv().addTextChangedListener(new TextWatcherEx() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
									  int count) {

				boolean isVisible = searchView.getTv().getText().toString().trim()
						.length() == 0; // 控制显示与否
				// 空的时候不显示
				if (isVisible) {
					searchView.getIv().setVisibility(View.INVISIBLE);
					//searchListView.setVisibility(View.INVISIBLE);
					adapter.updateListView(contactsListDpartment);
				} else {
					searchView.getIv().setVisibility(View.VISIBLE);

				}

			}
		});

		searchView.getTv().setOnEditorActionListener(
				new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView v, int actionId,
												  KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE
								|| actionId == EditorInfo.IME_ACTION_GO
								|| actionId == EditorInfo.IME_ACTION_NEXT
								|| actionId == EditorInfo.IME_ACTION_SEARCH) {
							// 搜索
							boolean isVisible = searchView.getTv().getText()
									.toString().length() >= 1;
							if (isVisible) {
								// 搜索
								String key_word = searchView.getTv().getText()
										.toString();

								if (contactsList != null){
									for (int i = 0; i < contactsList.size();i++){
										if (contactsList.get(i).getIscheck())
											contactsListSelect.add(contactsList.get(i));
									}
								}


								if (contactsList!=null){
									contactsList.clear();
								}

								searchService(key_word);
							}
						}
						return false;
					}
				});

		// 默认删除按钮不显示
		searchView.getIv().setVisibility(View.INVISIBLE);
	}

	/***
	 * 调用后台服务
	 * @param key_word
	 */
	private void searchService(String key_word) {
		JSONObject json = new JSONObject();
		try {

			json.put("transtype", "contactlist");
			json.put("uuidToken", Constant.TOKEN);
			json.put("tenant_id", getUserInfoLRY().getTenant_id());
			json.put("query", key_word);
			if (!CommonUtil.isNetworkConnected(this)) {
				CommonUtil.showToast(this, "当前网络不可用,请检查!");
				return;
			}
			MAServices_lib.callMACommonService(this, new ServiceCallback() {
				@Override
				public void execute(JSONObject json) {
					//Toast.makeText(mActivity, json+"", Toast.LENGTH_LONG).show();
					JSONObject jsObject;
					JSONArray jsArray;
					try {
						jsObject = (JSONObject) json.opt("result");
						Object obj = jsObject.opt("retflag");
						// 有错误的时候
						if (null != obj && obj.toString().trim().equals("1")) {
							String msg = jsObject.optString("msg").toString().trim();
							showMessage(msg);
							if(msg.contains("请重新登录")){
								turnToLoginActivity(SelectDepartmentActivity.this);
							}
							return;
						}
						jsArray = (JSONArray) jsObject.get("contacalist");
						contactsList = new ArrayList<ContactsVO>();
						for (int i = 0; i < jsArray.length(); i++) {
							ContactsVO contacts = new ContactsVO();
							contacts.setContactName(jsArray.getJSONObject(i).getString("user_name"));
							contacts.setVdef(jsArray.getJSONObject(i).getString("user_mobilephone"));
							contacts.setContactTel(jsArray.getJSONObject(i).getString("user_telephone"));
							contacts.setUser_email(jsArray.getJSONObject(i).getString("user_email"));
							contacts.setCuserId(jsArray.getJSONObject(i).getString("cuserid"));
							contactsList.add(contacts);
						}

						contactsList = filledData(contactsList);
						Collections.sort(contactsList, pinyinComparator);
						adapter.updateListView(contactsList);
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}

				@Override
				public void error(String arg0, String arg1) {
					// 设置登录按钮可用性(登录请求后台有反应后可用)
					Toast.makeText(SelectDepartmentActivity.this, arg0 + arg1,
							Toast.LENGTH_LONG).show();
				}
			}, json);

		} catch (Exception e) {
			// 设置登录按钮可用性(登录请求后台有反应后可用)
			Log.e("mmmm", e + "");
			e.printStackTrace();
		}

	}

	/**姓名首字母转换*/
	private List<ContactsVO> filledData(List<ContactsVO> contactsList){
		if (contactsList == null) {
			contactsList = new ArrayList<ContactsVO>();
		}
		for(int i=0; i<contactsList.size(); i++){
			String pinyin = characterParser.getSelling(contactsList.get(i).getContactName());
			String sortString = pinyin.substring(0, 1).toUpperCase();
			if(sortString.matches("[A-Z]")){
				contactsList.get(i).setSortLetters(sortString.toUpperCase());
			}else{
				contactsList.get(i).setSortLetters("#");
			}
		}
		return contactsList;

	}

}
